#!/bin/bash

set -e -u -x

pid=$1
if [ -z "$pid" ]; then
  echo "usage: $0 <pid>" >&2
  exit 1
fi

cgroup_mount="$(mktemp -d)"
trap "rm -rf $cgroup_mount" EXIT

devices_mount_info=$(cat /proc/$pid/cgroup | grep devices)

if [ -z "$devices_mount_info" ]; then
  # cgroups not set up; must not be in a container
  exit 0
fi

devices_subsytems=$(echo $devices_mount_info | cut -d: -f2)
devices_subdir=$(echo $devices_mount_info | cut -d: -f3)

if [ "$devices_subdir" = "/" ]; then
  # we're in the root devices cgroup; must not be in a container
  exit 0
fi

mount -t cgroup -o "$devices_subsytems" none "$cgroup_mount"

# permit our cgroup to do everything with all devices
# ignore failure in case something has already done this; echo appears to
# return EINVAL, possibly because devices this affects are already in use
echo a > "${cgroup_mount}${devices_subdir}/devices.allow" || true

# remove mount point so we can clean it up
umount "$cgroup_mount"
